﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HTTT.Bussiness;
using HTTT.DataAccess;
using HTTT.AD;
using System.Configuration;
using HTTT.Utilities;

namespace HTTT.admin.adgroup
{
    public partial class EditGroup : System.Web.UI.Page
    {
        /// <summary>
        ///  View State Username
        /// </summary>
        private Guid EditID
        {
            get
            {
                object obj = this.ViewState["_EditID"];
                if (obj == null)
                    return Guid.NewGuid(); //default to show ID : 0 
                else
                    return (Guid)obj;
            }
            set
            {
                this.ViewState["_EditID"] = value;
            }

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            string TempID = Request.QueryString["ID"];
            Guid MyID;
            bool convert = Guid.TryParse(TempID, out MyID);
            HT_GroupsBO UserBO = new HT_GroupsBO();
            if (convert)
            {
                EditID = MyID;
                string ouPath = LoadGroupDetail(EditID);
                LoadOU(ouPath);
            }
            else
            {
                Response.Redirect("GroupList.aspx");
            }
        }
        private void LoadOU(string selectedValue)
        {
            //Get OU list
            HT_OUBO Bo = new HT_OUBO();
            List<HT_OU> ListBO = Bo.GetAllHT_OU().ToList();
            ddlOU.DataSource = ListBO;
            ddlOU.DataValueField = ADOUProperties.DISTINGUISHEDNAME;
            ddlOU.DataTextField = ADOUProperties.NAME;
            ddlOU.DataBind();
            ddlOU.Items.Insert(0, new ListItem("▼ " + ConfigurationManager.AppSettings["LDAPDomain"], ConfigurationManager.AppSettings["DomainPath"]));
            ddlOU.SelectedValue = selectedValue;
        }
        private string LoadGroupDetail(Guid id)
        {
            //Get UserInfo by username
            HT_GroupsDAO dao = new HT_GroupsDAO();
            HT_Groups Info = dao.GetHT_GroupsByID(id);
            txtName.Text = Info.name;
            txtDescription.Text = Info.description;
            rblGroupScope.SelectedValue = Info.groupScope.ToString();
            rblGroupType.SelectedValue = Convert.ToInt16(Info.isSecurityGroup).ToString();
            txtMember.Text = Info.members;
            string ouPath = Info.LDAPPath;
            ouPath = ouPath.Substring(ouPath.IndexOf(',') + 1);
            return ouPath;
        }

        protected void btnModifyMember_Click(object sender, EventArgs e)
        {
            Response.Redirect("ModifyMemberGroup.aspx?ID=" + EditID);
        }
        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            ReturnValue<bool> Valid = ValidateData();
            if (Valid.RetValue)
            {
                if (SaveForm())
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "Redirect", Common.FormatMsgThenRedirect("Tạo yêu cầu sửa thành công", "GroupList.aspx"), true);
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "Message", Common.FormatAlertMsg(Valid.Msg), true);
            }

        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("GroupList.aspx");
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            ReturnValue<bool> Valid = ValidateData();
            if (Valid.RetValue)
            {
                HT_GroupsBO bo = new HT_GroupsBO();
                bool result = bo.RequestDeleteGroup(EditID, Page.User.Identity.Name, txtFromRequest.Text);
                if (result)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "Message", Common.FormatMsgThenRedirect("Tạo yêu cầu xóa tài khoản thành công !", "UserList.aspx"), true);
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "Message", Common.FormatAlertMsg(Valid.Msg), true);
            }

        }

        private ReturnValue<bool> ValidateData()
        {
            if (txtFromRequest.Text.Trim() == string.Empty) return new ReturnValue<bool>(false, "Phải nhập thông tin yêu cầu");
            if (txtName.Text.Trim() == string.Empty) return new ReturnValue<bool>(false, "Phải nhập tên Group");
            return new ReturnValue<bool>(true, "");
        }


        private bool SaveForm()
        {
            //Collec infomation
            HT_Request NewRequest = new HT_Request();
            HT_GroupsBO groupBO = new HT_GroupsBO();
            NewRequest.ID = Guid.NewGuid();
            NewRequest.Action = HT_ACTION.EDIT_GROUP.ToString();
            String distigutedName = "CN=" + txtName.Text.Trim() + ",";
            distigutedName += ddlOU.SelectedValue;
            NewRequest.ActionDescription = groupBO.BuildEditGroupString(
                                            txtName.Text
                                            , txtDescription.Text
                                            , distigutedName
                                            , Convert.ToInt16(rblGroupScope.SelectedValue)
                                            , Convert.ToInt16(rblGroupType.SelectedValue)
                                            , txtMember.Text
                                            );
            string OUName = ddlOU.SelectedItem.Text;
            OUName = OUName.Substring(OUName.IndexOf("├ ") + 1);
            NewRequest.ActionName = "Sửa Group  <strong>" + txtName.Text + "</strong>";
            NewRequest.Status = Utilities.HT_REQUESTSTATUS.PEDDING.ToString();
            NewRequest.Note = txtFromRequest.Text.Trim();
            NewRequest.RequestDate = DateTime.Now;
            NewRequest.Requestedby = Page.User.Identity.Name;
            HT_RequestBO re = new HT_RequestBO();
            Boolean result = re.InsertRequest(NewRequest);
            return result;
        }
    }
}